package com.trepadora.mapper;

import java.io.IOException;

import net.sf.json.JSONObject;

import com.fourspaces.couchdb.Document;
import com.fourspaces.couchdb.View;
import com.fourspaces.couchdb.ViewResults;
import com.trepadora.model.Room;

/**
 * 
 * @author Karol Lotkowski
 * 
 */
public class RoomMapper extends CouchDBMainMapper {

	/**
	 * 
	 * Save room in DB
	 * 
	 * @param hostId
	 * @param guestId
	 * @param state
	 * @throws IOException
	 * 
	 * @return document id
	 */
	public String saveRoom(final String hostId, final String guestId, final String streamIn,
			final String streamOut, final Boolean active) throws IOException {

		Document roomDoc = new Document();
		roomDoc.put("type", "room");
		roomDoc.put("hostId", hostId);
		roomDoc.put("guestId", guestId);
		roomDoc.put("active", active);
		roomDoc.put("streamIn", streamIn);
		roomDoc.put("streamOut", streamOut);
		
		db.saveDocument(roomDoc);
		
		return roomDoc.getId();
	}
	
	/**
	 * Change active state for selected room
	 * 
	 * @param roomId
	 * @param state
	 * @throws IOException
	 */
	public boolean setActiveState(final String roomId, final boolean state) throws IOException {
		
		Document roomDoc = db.getDocument(roomId);
		roomDoc.put("active", state);
		
		db.saveDocument(roomDoc);
		
		return state;
	}
	
	/**
	 * Get chat room where userId is like a guest
	 * 
	 * @param userId
	 * 
	 * @return Room
	 */
	public Room getOpenRoomByUser(final String userId){
		
		Room room = null;
		
		// Find chat room assigned to user
		View guestRoom = new View(buildViewDoc("room", "roomByGuest"));
		guestRoom.setKeyString(userId);
		
		ViewResults openRoomResults = db.view(guestRoom);
		
		if(openRoomResults.getResults().size() > 0){			
			Document roomDoc = openRoomResults.getResults().get(0);
			
			if (roomDoc != null){
				JSONObject value = (JSONObject) roomDoc.get("value");
				
				room = new Room(roomDoc.getId(), value.getString("hostId"), roomDoc.getString("key"), value.getString("streamIn"), value.getString("streamOut"),  true);
			}
		}
		
		return room;
	}
}
